package com.lp.company.service;

import com.lp.common.utils.IdWorker;
import com.lp.company.dao.DepartmentDao;
import com.lp.domain.company.Department;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * @author lipengak
 * @Description
 * @Date 2020/1/31 16:43
 * @Copyright 2019-2020
 */
@Service
public class DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;


    @Autowired
    private IdWorker idWorker;

    /**
     * CURD
     */
    public Department findById(String id) {
        return departmentDao.findById(id).get();
    }

    public void add(Department department) {
        department.setId(idWorker.nextId() + "");
        departmentDao.save(department);
    }

    public void update(Department department) {
        Department temp = departmentDao.findById(department.getId()).get();
        BeanUtils.copyProperties(department, temp);
        departmentDao.save(temp);
    }

    public void deleteById(String id) {
        departmentDao.deleteById(id);
    }

    /**
     * 查询列表
     */
    public List<Department> findAll(String companyId) {
        /**
         * 构建SPecification查询条件
         */
        Specification<Department> spec = new Specification<Department>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                return cb.equal(root.get("companyId").as(String.class),companyId);
            }
        };
        return departmentDao.findAll(spec);
    }

}
